<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="资产名称" prop="assetName">
        <el-input
          v-model="formData.assetName"
          placeholder="请选择资产名称"
          readonly
          @click="handleSelectAssete"
        />
      </el-form-item>

      <el-form-item label="维修日期" prop="repairDate">
        <el-date-picker
          v-model="formData.repairDate"
          type="date"
          value-format="x"
          placeholder="选择维修日期"
        />
      </el-form-item>
      <el-form-item label="维修费用" prop="repairCost">
        <el-input v-model="formData.repairCost" placeholder="请输入维修费用" />
      </el-form-item>

      <el-form-item label="跟进人" prop="follower">
        <UserSelect @node-change="handleNodeChange" v-model="formData.userId"  />
      </el-form-item>

      <el-form-item label="维修原因" prop="repairReason">
        <el-input v-model="formData.repairReason" placeholder="请输入维修原因" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { AssetRepairApi, AssetRepairVO } from '@/api/oa/assetrepair'
import UserSelect from '@/views/system/user/UserSelect.vue'
import { AssetInfoApi } from '@/api/oa/assetinfo'
import { defineProps } from 'vue'
import * as UserApi from '@/api/system/user'

/** 资产报修记录 表单 */
defineOptions({ name: 'AssetRepairForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  assetName: undefined,
  assetCategory: undefined,
  assetBrand: undefined,
  model: undefined,
  repairDate: undefined,
  repairCost: undefined,
  repairReason: undefined,
  userId: undefined,
  userName: undefined,
  recordTime: undefined
})
const props = defineProps({
  assetName: {
    type: [Number, String],
    required: true
  }
})
const formRules = reactive({
  assetName: [{ required: true, message: '资产名称不能为空', trigger: 'blur' }],
  assetCategory: [{ required: true, message: '资产分类不能为空', trigger: 'change' }],
  assetBrand: [{ required: true, message: '资产品牌不能为空', trigger: 'change' }],
  repairDate: [{ required: true, message: '维修日期不能为空', trigger: 'blur' }],
  repairCost: [{ required: true, message: '维修费用不能为空', trigger: 'blur' }],
  repairReason: [{ required: true, message: '维修原因不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '跟进人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref




const handleSelectAssete = async () => {
  try {
    const id = props.assetName // ✅ 正确获取当前车辆ID
    console.log(id)
    await openDetail('view', id)
  } catch (error) {
    message.error('加载车辆信息失败')
  }
}
const detailRef = ref()
const openDetail = async (type: string, id?: number) => {
  if (!id) {
    message.error('未找到对应的ID')
    return
  }
  try {
    const rowData = await AssetInfoApi.getAssetInfo(id)
    console.log(rowData)

    // 回填数据
    formData.value.assetName = rowData.name

    // 如果需要弹窗展示详情也可以继续调用 detailRef
    if (detailRef.value && typeof detailRef.value.open === 'function') {
      detailRef.value.open(type, rowData)
    }
  } catch (error) {
    message.error('获取资产信息失败')
  }
}
const setFollowerInfo = (row) => {
  console.log('【UserSelect】选中用户对象:', row)
  formData.value.userId = row?.id
  formData.value.userName = row?.nickname
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if (id) {
    formLoading.value = true
    try {
      // 获取维修记录数据
      const data = await AssetRepairApi.getAssetRepair(id)
      formData.value = data

      // ✅ 如果有 follower ID，请求用户信息并填充 nickName
      if (formData.value.userId) {
        const user = await UserApi.getUser(formData.value.userId)
        if (user && user.nickname) {
          setFollowerInfo(user)
        }
      }

    } finally {
      formLoading.value = false
    }
  } else {
    // 新增模式
    if (props.assetName) {
      try {
        const res = await AssetInfoApi.getAssetInfoPage({ assetName: props.assetName })
        if (res && res.list && res.list.length > 0) {
          const asset = res.list[0]
          formData.value.assetName = asset.assetName
          formData.value.assetCategory = asset.assetCategory
          formData.value.assetBrand = asset.assetBrand
          formData.value.model = asset.model
        } else {
          message.warning('未找到对应的资产信息')
        }
      } catch (err) {
        message.warning('获取资产信息失败')
      }
    }
  }
}


defineExpose({ open ,openDetail}) // 提供 open 方法，用于打开弹窗


const assetList = ref([]) // 资产列表
const getAssetList = async () => {
  try {
    const res = await AssetInfoApi.getAssetInfoPage({})
    assetList.value = res.list || []
  } catch (error) {
    console.error('获取资产列表失败', error)
  }
}

const handleAssetChange = (selectedName: string) => {
  const selectedAsset = assetList.value.find(asset => asset.assetName === selectedName)
  if (selectedAsset) {
    formData.value.assetCategory = selectedAsset.assetCategory
    formData.value.assetBrand = selectedAsset.assetBrand
    formData.value.model = selectedAsset.model
  }
}


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AssetRepairVO
    if (formType.value === 'create') {
      await AssetRepairApi.createAssetRepair(data)
      message.success(t('common.createSuccess'))
    } else {
      await AssetRepairApi.updateAssetRepair(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    assetName: undefined,
    assetCategory: undefined,
    assetBrand: undefined,
    model: undefined,
    repairDate: undefined,
    repairCost: undefined,
    repairReason: undefined,
    userId: undefined,
    userName: undefined,
    recordTime: undefined
  }
  formRef.value?.resetFields()
}
const handleNodeChange = async (row) =>{
  setFollowerInfo(row)
}

onMounted(() => {
  getAssetList()
})
</script>
